using EasyXaf.LowCode.RulesEngineEditors.Models;
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using Newtonsoft.Json;

namespace EasyXaf.LowCode.RulesEngineEditors;

public partial class RulesEngineRenderer
{
    private string WorkflowEleId { get; } = $"id-{Guid.NewGuid()}";

    private IJSObjectReference JsModule { get; set; }

    private WorkflowObject Workflow { get; set; }

    [Parameter]
    public RulesEngineModel Model { get; set; }

    [Inject]
    private IJSRuntime JSRuntime { get; set; }

    private async Task RulesChangedAsync()
    {
        var json = JsonConvert.SerializeObject(Workflow.ToWorkflow());
        Model.Value = json;
        await Model.ValueChanged.InvokeAsync(json);
    }

    protected override void OnInitialized()
    {
        base.OnInitialized();

        var rulesEngineWorkflow = new RulesEngineWorkflow();

        if (!string.IsNullOrWhiteSpace(Model.Value))
        {
            rulesEngineWorkflow = JsonConvert.DeserializeObject<RulesEngineWorkflow>(Model.Value);
        }

        Workflow = WorkflowObject.FromWorkflow(rulesEngineWorkflow);
        Workflow.Validate();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            var jsModuleFile = "./_content/EasyXaf.LowCode.RulesEngineEditors/RulesEngineRenderer.razor.js";
            JsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", jsModuleFile);
            await JsModule.InvokeVoidAsync("init", WorkflowEleId);
        }
    }
}